#!usr/bin/env python
# *- coding:utf-8 -*-
# Andy Create @ 11/15/2019 11:12 AM
from api import models


class Memory(object):
    def process(self, memory, server_object):
        if not memory['status']:
            print('内存信息错误', memory['error'])
            return
        memory_info = memory['data']
        new_memory_slot_set = set(memory_info.keys())

        db_memory_queryset = models.Memory.objects.filter(server=server_object)
        db_memory_dict = {obj.slot: obj for obj in db_memory_queryset}
        db_memory_slot_set = set(db_memory_dict.keys())

        record_msg_list = []

        # 新增的内存
        create_slot_set = new_memory_slot_set - db_memory_slot_set
        create_object_list = []
        for slot in create_slot_set:
            create_object_list.append(models.Memory(**memory_info[slot], server=server_object))
        if create_object_list:
            models.Memory.objects.bulk_create(create_object_list, batch_size=10)
            msg = "[%s新增内存" % ",".join(create_slot_set)
            record_msg_list.append(msg)

        # 要删除的内存
        remove_slot_set = db_memory_slot_set - new_memory_slot_set
        models.Memory.objects.filter(server=server_object, slot__in=remove_slot_set).delete()
        if remove_slot_set:
            msg = "[删除内存]在%s槽删除了内存" % ",".join(remove_slot_set)
            record_msg_list.append(msg)

        # 更新内存
        update_slot_set = new_memory_slot_set & db_memory_slot_set
        for slot in update_slot_set:
            temp = []

            row_dict = memory_info[slot]
            row_object = db_memory_dict[slot]
            for key, value in row_dict.items():
                if value != getattr(row_object, key):
                    msg = "%s由%s变更为%s" % (key, getattr(row_object, key), value)
                    temp.append(msg)
                    setattr(row_object, key, value)
            if temp:
                slot_msg = "更新内存 槽位%s:%s" % (slot, "".join(temp))
                record_msg_list.append(slot_msg)
                row_object.save()
        if record_msg_list:
            models.Record.objects.create(server=server_object, content="\n".join(record_msg_list))
